package eafit.sicom.mpark;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import eafit.sicom.mpark.entity.ParkingSlot;

/***
 * Main class,
 * 
 * @author SICOM
 * 
 */
public class MParkActivity extends Activity {
	/**  */
	private final int TIME_SCHEDULE_UPDATE = 10000; // ms
	private int timeScheduleUpdateParking = 20000; // ms
	boolean automaticMode = true;
	TextView textViewMode;

	/** Instance to manage every external data */
	MparkModel parkingModel;
	Handler handlerUpdate;
	Timer timer;
	ProgressDialog dialog;

	// TimerRefreshConection trc;
	String FILENAME = "hello_file";

	FileOutputStream fos;

	Date horaActual;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
	  	
		// Carga la interfaz de la pantalla principal
		setContentView(R.layout.main);
		getParkingPreferences();
		// Log.d("*****************", "P** On Create");
		
		parkingModel = new MparkModel(this);
		textViewMode = (TextView) findViewById(R.id.textViewMode);
		
		if (automaticMode) {

			parkingModel.registerLocationListenerGPS();
			
			// Inicia el temporizador encargado de actualizar la disponibilidad
			initScheduleUpdateTime();
			initScheduleUpdateParkings();
			// initTimerRefreshConn();
			horaActual = new Date();

			dialog = ProgressDialog.show(MParkActivity.this, "",
					"Loading. Please wait...", true);

		}
	

		// Hace que la vista no se rote, que se quede en portrait todo el tiempo
		// this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

	@Override
	protected void onResume() {
		getParkingPreferences();
		if(automaticMode){
			textViewMode.setText(R.string.auto_mode);
			parkingModel.registerLocationListenerGPS();
		}
		else{
			textViewMode.setText(R.string.manual_mode);	
		}
		

		horaActual = new Date();

		//grabarTxt(horaActual.toString() + ": onResume");
		super.onResume();
	}
 
	@Override
	protected void onPause() {
		if(automaticMode){
		//textViewMode.setText(R.string.auto_mode);
		parkingModel.removeUpdatesGPS();
		}
		horaActual = new Date();

		//grabarTxt(horaActual.toString() + ": onPause");
		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_mpark, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		// Handle item selection
		switch (item.getItemId()) {

		case R.id.itemUpdate:

			updateFreeParkingSlots();

			return true;

		case R.id.itemPreferences:

			Intent settingsActivity = new Intent(getBaseContext(),
					Preferences.class);

			startActivity(settingsActivity);

			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Initialize the timer that schedule the "update"
	 */
	private void initScheduleUpdateTime() {
		horaActual = new Date();

		////grabarTxt(horaActual.toString() + ": initScheduleUpdateTime");

		Handler handlerUpdate = new Handler();

		handlerUpdate.postDelayed(new Runnable() {

			public void run() {
				updateTime();

				initScheduleUpdateTime();// el handler llama una sola vez, esto
											// es para que se vuelva a llamar
											// ciclicamente

			}
		}, TIME_SCHEDULE_UPDATE);

	}

	/**
	 * Initialize the timer that schedule the update of free parking slots
	 */
	private void initScheduleUpdateParkings() {
		horaActual = new Date();

		//grabarTxt(horaActual.toString() + ": initScheduleUpdateParkings");
		//grabarTxt(horaActual.toString()
				//+ ": initScheduleUpdateParkings, timeScheduleUpdateParking: "
				//+ timeScheduleUpdateParking);
		// Crea el temporizador y se define el tiempo de actualizacion
		handlerUpdate = new Handler();
		handlerUpdate.postDelayed(new Runnable() {
			public void run() {
				// Recupera y actualiza en pantalla la disponibilidad de
				// parqueaderos
				updateFreeParkingSlots();
				initScheduleUpdateParkings();// el handler llama una sola vez,
												// esto es para que se vuelva a
												// llamar ciclicamente
			}
		}, timeScheduleUpdateParking);
	}

	/**
	 * Manage the time between each update of the free parking slots
	 */
	private void updateTime() {
		horaActual = new Date();

		//grabarTxt(horaActual.toString() + ": updateTime");
		// Get the new time based on GPS
		timeScheduleUpdateParking = parkingModel.calcUpdateTime();
		//grabarTxt(horaActual.toString()
				//+ ": updateTime,timeScheduleUpdateParking: "
				//+ timeScheduleUpdateParking);

	}

	/**
	 * Manage the update of the free parking slots
	 */
	private void updateFreeParkingSlots() {
		horaActual = new Date();

		//grabarTxt(horaActual.toString() + ": updateFreeParkingSlots");
		try {
			// Recupera la disponibilidad en los parkeaderos
			ParkingSlot parkingSlots = parkingModel.getFreeParkingSlots();
			// Actualiza la informacion en pantalla
			TextView textviewNorth = (TextView) findViewById(R.id.textViewNorth);
			TextView textviewSouth = (TextView) findViewById(R.id.textViewSouth);
			textviewNorth.setText(String.valueOf(parkingSlots.getFreeNorth()));
			textviewSouth.setText(String.valueOf(parkingSlots.getFreeSouth()));
		} catch (Exception e) {
			e.printStackTrace();
			// Muestra en pantalla si ocurrio un exception
			Toast.makeText(this.getApplicationContext(),
					"Exception: " + e.getMessage(), Toast.LENGTH_SHORT);
		}
		if(automaticMode)
		dialog.cancel();
	}

	// private void initTimerRefreshConn() {
	// timer = new Timer();
	// trc = new TimerRefreshConection();
	// timer.schedule(trc, 0, timeScheduleUpdateParking);
	// }
	//
	// private class TimerRefreshConection extends TimerTask{
	// @Override
	// public void run() {
	// //Recupera y actualiza en pantalla la disponibilidad de parqueaderos
	// updateFreeParkingSlots();
	// }
	// }


	public void getParkingPreferences() {
		SharedPreferences preferences = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		
		automaticMode = preferences.getBoolean("checkbox_auto_mode", true);
		//Toast.makeText(getApplicationContext(), automaticMode + "",
			//	Toast.LENGTH_SHORT).show();
	}
}